'''
Created on Feb 14, 2014

@author: yfrank
'''
from Commands.Message import InputMessage as InputMessage

import Transport.IOHandler as IOHandler

import Transport.PeerTable as PeerTable

import RoboticsPeer


class Client(object):

    def __init__(self,host):

        self.host = host
        self.peer_table = PeerTable.PeerTable()
        self.iohandler = IOHandler.IOHandler(self.peer_table)


    def connect(self,addr):
        peer = self.peer_table.get_peer(addr)
        if not peer:
            peer = RoboticsPeer.RoboticsPeer(self.host)
        if peer.isClosed(): peer.connect(addr)
        self.peer_table.add_peer(peer,addr)

    def start(self):
        self.iohandler.start()

    def stop(self):
        self.iohandler.stop()

    def send_input(self,path,addr):

        f = open(path+'workspace.txt','r')
        workspace = f.read()
        f.close()
        f = open(path+'robot.txt','r')
        robot = f.read()
        f.close()
        f = open(path+'source.txt','r')
        src = f.read()
        f.close()
        f = open(path+'target.txt','r')
        trg = f.read()
        f.close()
        message = InputMessage(workspace,robot,src,trg)
        self.send(str(message),addr)


    def send(self,buff,addr):
        return self.iohandler.send(buff,addr)


if __name__ == '__main__':

    indir = "..\\input\\"
    outdir = "..\\output\\"
    localhost = "127.0.0.1"

    #log on to ad hoc network: robotics password: simulation101
    # figure out your IP address using ipconfig for example: 132.67.173.179
    addr = (localhost,9221)
    client = Client(localhost)
    client.start()
    client.connect(addr)
    client.send_input(indir,addr)




